package com.cainaer.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cainaer.orders.api.RemoteOrdersService;
import com.cainaer.orders.api.domain.OrderItem;
import com.cainaer.product.api.RemoteProductService;
import com.cainaer.shop.config.AMapUtils;
import com.cainaer.shop.config.Calculate;
import com.cainaer.shop.config.LngLat;
import com.cainaer.shop.domain.ShopInfo;
import com.cainaer.shop.domain.VegetableMarket;
import com.cainaer.shop.domain.vo.VegetableMarketVo;
import com.cainaer.shop.mapper.ShopInfoMapper;
import com.cainaer.shop.mapper.VegetableMarketMapper;
import com.cainaer.shop.service.IVegetableMarketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 菜市场表 服务实现类
 * </p>
 *
 * @author Tina
 * @since 2020-09-03
 */
@Service
public class VegetableMarketServiceImpl extends ServiceImpl<VegetableMarketMapper, VegetableMarket> implements IVegetableMarketService {

//    @Autowired
//    private VegetableMarketMapper vegetableMarketMapper;

    //市场Service
    @Autowired
    private VegetableMarketMapper vegetableMarketMapper;

    //商家Service
    @Autowired
    private ShopInfoMapper shopInfoMapper;

    //订单Service
    @Autowired
    private RemoteOrdersService remoteOrdersService;

    //评论Service
    @Autowired
    private RemoteProductService remoteProductService;

    /**
     *  查询附近市场列表
     *
     * @param vegetableMarket
     * @return
     */
    @Override
    public  List<VegetableMarketVo> queryVegetableMarket(VegetableMarket vegetableMarket,Integer condition) {
        //条件查询这个地区的市场
        QueryWrapper<VegetableMarket> queryWrapper = new QueryWrapper<>();
        /*queryWrapper.eq("province",vegetableMarket.getProvince());
        queryWrapper.eq("city",vegetableMarket.getCity());
        queryWrapper.eq("district",vegetableMarket.getDistrict());*/
        List<VegetableMarket> vegetableMarketList = vegetableMarketMapper.selectList(queryWrapper);
        //实例化菜市场的VoList，装这个地区的所有菜市场的详情信息
        List<VegetableMarketVo> vegetableMarketVos =new ArrayList<VegetableMarketVo>();
        //市场总月销量
        Integer marketSalesVolume=0;
        //市场总月评价级别
        double marketAvgComment=0;
        // 店铺月总评价级别平均数
        double shopAvgLevel=0;
        //市场每个店铺总月评价总数量
        Integer shopCommentCount=0;
        if (vegetableMarketList.size()>0){
            for (int i = 0; i < vegetableMarketList.size(); i++) {
                //实例化菜市场的Vo类，装菜市场的详情信息
                VegetableMarketVo vegetableMarketVo=new VegetableMarketVo();
                //往菜市场的Vo类，添加菜市场信息
                vegetableMarketVo.setVegetableMarket(vegetableMarketList.get(i));
                //开始地址
                LngLat start = new LngLat(Double.parseDouble(vegetableMarketList.get(i).getLongitude()), Double.parseDouble(vegetableMarketList.get(i).getLatitude()));
                //结束地址
                LngLat end = new LngLat(Double.parseDouble(vegetableMarket.getLongitude()),Double.parseDouble(vegetableMarket.getLatitude()));
                //计算两点距离，以公里为单位
                double distance1=AMapUtils.calculateLineDistance(start, end);//1000
                //判断市场和目的地距离有没有一公里
                if (distance1<1000){
                    BigDecimal b = new BigDecimal(distance1);
                    //保留两位小数
                    double distance2 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    vegetableMarketVo.setDistanceUnit(distance2+"米");
                }else {
                    BigDecimal b = new BigDecimal(distance1/1000);
                    //保留两位小数
                    double distance2 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    vegetableMarketVo.setDistanceUnit(distance2+"公里");
                }
                distance1=distance1/1000;
                BigDecimal b = new BigDecimal(distance1);
                //保留两位小数
                double distance2 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                //输入配送距离
                vegetableMarketVo.setDistance(distance2);

                //输入配送时间
                vegetableMarketVo.setDeliveryTime("50分钟");
                //判断路段大于5公里
                if (distance2>5){
                    vegetableMarketVo.setDeliveryTime(Calculate.calculateDeliveryTime(distance2));
                }
                //根据市场id条件查询市场内的商店
                QueryWrapper<ShopInfo> queryShopInfo = new QueryWrapper<>();
                queryShopInfo.eq("market_id",vegetableMarketList.get(i).getMarketId());
                List<ShopInfo> shopInfos = shopInfoMapper.selectList(queryShopInfo);

                //判断这个菜市场是否有商铺
                if (shopInfos.size()>0){
                    for (int j = 0; j < shopInfos.size(); j++) {
                        //根据商店ID条件查询每个商店的月销量，进行相加，得出总销量
                        marketSalesVolume += remoteOrdersService.selectOrderAmountByShopId(shopInfos.get(j).getShopId());

                        //根据店铺ID查询订单商品ID信息
                        List<Long> OrderItemProductIds = remoteOrdersService.selectOrderItemProductIdListsByShopId(shopInfos.get(j).getShopId());
                        ///如果这个店铺有订单，订单商品信息数量大于0的
                        if (OrderItemProductIds.size()>0){
                            //循环订单商品信息，查找这个月这个商品的平均评价级别
                            for (int z=0;z<OrderItemProductIds.size();z++){
                                System.out.println("商品ID:::"+OrderItemProductIds.get(z).longValue());
                                double AvgLevel=remoteProductService.selectCommentAvgLevelByProductId(OrderItemProductIds.get(z).longValue());
                                //如果这个商品有人评价就一定大于0
                                if (AvgLevel>0){
                                    //把这个市场的店铺月总评价级别平均数累加
                                    shopAvgLevel+=AvgLevel;
                                    //把市场每个店铺总月评价数量累加，得出评论总数量
                                    shopCommentCount++;
                                }
                            }
                        }


                    }
                    //把查询出来市场的每个商店的月评价级别总和（店铺月总评价级别平均数），除以评价数量（市场每个店铺总月评价总数量），等于市场平均评价级别
                    marketAvgComment=shopAvgLevel/shopCommentCount;
                }

                //输入总月销量
                vegetableMarketVo.setSalesVolume(marketSalesVolume);

                //输入市场评价级别
                vegetableMarketVo.setEvaluate(marketSalesVolume);

                //把市场信息添加进list
                vegetableMarketVos.add(vegetableMarketVo);


            }
            Calculate.Sort(vegetableMarketVos,condition);
        }

        System.out.println(vegetableMarketVos);


        return vegetableMarketVos;

    }


}
